package servlet;

import java.io.IOException;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import entity.Order;
import service.OrderService;
import service.impl.OrderServiceImpl;

/**
 * Servlet implementation class OrderServlet
 */
@WebServlet(name="OrderServlet",urlPatterns="/orderServlet")
public class OrderServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
	
	private OrderService orderService = new OrderServiceImpl();
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		String action = request.getParameter("action");
		if (action != null && action.length()>0) {
			switch (action) {
			case "add":
				add(request,response); //下单
				break;
			case "topay":
				topay(request,response); //去支付页面
				break;
			default:
				response.sendRedirect("404.jsp");
				break;
			}
		} else {
			response.sendRedirect("404.jsp");
		}
		
	}
	private void topay(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String orderNO = request.getParameter("orderNO");
		Order order = orderService.findByOrderNO(orderNO);
		request.setAttribute("order", order);
		request.getRequestDispatcher("pay.jsp").forward(request, response);
	}
	
	private void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//商户订单号，商户网站订单系统中唯一订单号，必填
		String orderNO = UUID.randomUUID().toString();
		//付款金额，必填
		String amount = request.getParameter("amount");
		//主题，必填
		String subject = request.getParameter("subject");
		//商品描述，可空
		String phone = request.getParameter("phone");
		String body = "充值号码："+phone+"，充值金额："+amount+"元";
		
		Order order = new Order();
		order.setAmount(Double.parseDouble(amount));
		order.setBody(body);
		order.setOrderNO(orderNO);
		order.setPhone(phone);
		order.setStatus(0); // 0待支付状态,1已支付
		order.setSubject(subject);
		
		int result = orderService.add(order);
		
		if (result > 0) {
			//跳转到支付页面
			response.sendRedirect("orderServlet?action=topay&orderNO="+order.getOrderNO());
		} else {
			//下单失败
			request.setAttribute("error", "下单失败");
			request.getRequestDispatcher("404.jsp").forward(request, response);
		}
		
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
